<?php
/**
 * Created by PhpStorm.
 *
 * Author : Traveler.
 * Time   : 2020/3/15 20:49
 * Company: Inner Mongolia Zhengzhi Network Technology Co., Ltd
 */

namespace app\admin\controller;


use app\admin\BaseController;
use app\admin\middleware\Auth;
use app\admin\middleware\Login;
use app\admin\model\Log as LogModel;
use app\admin\model\Menu as MenuModel;
use think\facade\View;

class Log extends BaseController
{
    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [
        Auth::class => ['only' => ['clear']],
        Login::class,
    ];

    /**
     * 接口：获取场所分类(表格渲染)
     * @return \think\response\Json
     */
    public function getTableData()
    {
        $param = $this->request->param();
        $data  = LogModel::getLogTable($param);

        return $this->success('获取日志成功', $data['data'], ['count' => $data['count']]);
    }

    /**
     * 页面渲染：日志管理
     * @return string
     */
    public function index()
    {
        // 权限标识
        $flag = [
            'clear' => 'log:clear',
        ];

        return View::assign('flag', $flag)->fetch();
    }

    /**
     * 生成日志
     * @param string $action 操作
     * @return LogModel|\think\Model
     */
    public static function generate(string $action = '未知操作')
    {
        $url = '/' . app('http')->getName() . '/' . request()->controller() . '/' . request()->action();
        $menu = MenuModel::where('url', $url)->find();

        $module = is_null($menu) ? '未知业务模块' : (0 == $menu['type'] ? $menu['name'] : MenuModel::find($menu['pid'])['name']);

        $data = [
            'staff_id' => session('admin_id'),
            'module'   => $module,
            'action'   => $action,
            'url'      => $url,
            'method'   => request()->method(),
            'ip'       => request()->ip(),
        ];

        return LogModel::create($data);
    }

    /**
     * 清空日志
     * @return \think\response\Json
     */
    public function clear()
    {
        $result = LogModel::select()->delete();

        if ($result) {
            return $this->success('清空成功');
        }

        return $this->error('清空失败');
    }
}